package data

import (
	"context"
	"errors"
	ke "github.com/go-kratos/kratos/v2/errors"
	"gorm.io/gorm"
	"paint-guess/internal/biz"
)

func (rp *paintGuessRepo) GetCountByRoomId(ctx context.Context, roomId string) (int64, error) {
	var count int64
	result := rp.data.db.Table("user_room").Where("room_id = ?", roomId).Count(&count)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return 0, nil
		}
		return 0, ke.New(500, "server error", "GetRoomPersonNum error, roomId:"+roomId)
	}
	return count, nil
}

func (rp *paintGuessRepo) InsertUserRoom(ctx context.Context, roomId, userId, nickname string, identity uint32) error {
	userRoom := biz.UserRoom{
		RoomId:   roomId,
		UserId:   userId,
		Identity: identity,
		Nickname: nickname,
	}

	result := rp.data.db.Create(&userRoom)
	return result.Error
}

func (rp *paintGuessRepo) DeleteUserRoom(ctx context.Context, userId string) (int64, error) {
	var userRoom biz.UserRoom
	result := rp.data.db.Where("user_id = ?", userId).Delete(&userRoom)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}

func (rp *paintGuessRepo) GetUserRoomMsgByUserId(ctx context.Context, userId string) (*biz.UserRoom, error) {
	var userRoom biz.UserRoom
	result := rp.data.db.Where("user_id = ?", userId).First(&userRoom)
	if result.Error != nil {
		return nil, result.Error
	}
	return &userRoom, nil
}

func (rp *paintGuessRepo) GetUserRoomMsgByRoomId(ctx context.Context, roomId string) ([]biz.UserRoom, error) {
	var userMsg []biz.UserRoom
	result := rp.data.db.Where("room_id = ?", roomId).Find(&userMsg)
	if result.Error != nil {
		return nil, result.Error
	}
	return userMsg, nil
}

func (rp *paintGuessRepo) UpdateUserScore(ctx context.Context, userId string, score int64) (int64, error) {
	var count int64
	res := rp.data.db.Table("user_room").Where("user_id = ?", userId).Update("score", score)
	count = res.RowsAffected
	if res.Error != nil {
		return 0, res.Error
	}
	return count, nil
}
